package com.zuxia.utils;

import com.zuxia.entity.JwtInfo;
import io.jsonwebtoken.Claims;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisTokenUtil {
    private String token="user:token:";
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static String newToken;

    //存储tokne
    public void setToken(JwtInfo jwtInfo, String accessToken, Long time){
        stringRedisTemplate.opsForValue().set(accessToken,JwtUtils.getJwtToken(jwtInfo,time),time, TimeUnit.DAYS);
    }

    public String getToken(String accessToken){
        return stringRedisTemplate.opsForValue().get(accessToken);
    }

    public void changeToken(String accessToken, String newAccessToken, String refreshToken){
        Long keyTtl = getKeyTtl(accessToken);
        System.out.println(keyTtl);
        stringRedisTemplate.opsForValue().set(newAccessToken,refreshToken,keyTtl, TimeUnit.MINUTES);
        stringRedisTemplate.delete(accessToken);
        setNewToken(newAccessToken);
    }

    public Long getKeyTtl(String key) {
        return stringRedisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.ttl(key.getBytes());
            }
        });
    }

    public void setNewToken(String jwt){
        this.newToken=jwt;
    }

    public String getNewToken(){
        return newToken;
    }
}
